<?php
/**
 * Created by PhpStorm.
 * User: moquan
 * Date: 2018/6/11
 * Time: 17:07
 */

namespace app\lib\exception;


use \Exception as Exception;
use think\exception\Handle;
use think\Request;

class ExceptionHandler extends Handle{

    private $code;

    private $msg;

    private $errorCode;

    public function render(Exception $e) {
        if( $e instanceof BaseException ){
            $this->code = $e->code;
            $this->msg = $e->msg;
            $this->errorCode = $e->errorCode;
        }else{
            $switch = config('app_debug');
            if( $switch ){
                return parent::render( $e );
            }else{
                $this->code = 500;
                $this->msg = "服务器错误";
                $this->errorCode = 999;
//                $this->recordErrorLog( $e );
            }
        }
        $Request = Request::instance();
        $result = [
            'msg' => (array)$this->msg,
            'error_code' => $this->errorCode,
            'request_url' => $Request->url(),
        ];
//        return view( "/public/alert", array( 'error' => $result ) );
//        return json($result, $this->code);
        return json($result);
    }

    /*protected function recordErrorLog( Exception $e ){
        Log::init([
            'type'  => 'file',
            // 日志保存目录
            'path'  => LOG_PATH,
            // 日志记录级别
            'level' => ['error','sql'],
        ]);
        Log::record( $e->getMessage(), 'error' );
    }*/
}